
package com.itcs.box.server.resolver;

import com.alibaba.fastjson.JSON;
import com.itcs.box.BoxConstants;
import com.itcs.box.domain.BoxResponse;
import com.itcs.box.server.server.NettyChannelMap;
import com.itcs.box.server.service.SecurityService;
import com.itcs.box.util.LogUtils;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 功能描述:
 * <app发送通讯盒交易广播接收服务>
 *
 * @ClassName: AppTopicBoxResolver
 * @Author: wanghui
 * @Date: 2019年05月17日 09:36:30
 *
 * @Copyright: 2019 Inc. All rights reserved. 注意: 本内容仅限于内部传阅,禁止外泄以及用于其他的商业目
 */
@Component
public class AppTopicBoxResolver {

	private Log logger = LogFactory.getLog(getClass());
	
	@Autowired
	private SecurityService securityService;

	public void subBoxMsg(String jsonStr) {
		try {
			BoxResponse boxResponse = JSON.parseObject(jsonStr, BoxResponse.class);

			// 明文域加密
			boxResponse = securityService.plainTextEncrypt(boxResponse);
			
			//添加MAC
			boxResponse.setKey(securityService.getSecurityMac(boxResponse));
			
			if (boxResponse.getKey() == null) {
				boxResponse.setKey("");
			}
			
			logger.info(JSON.toJSONString(boxResponse));
			
			String deviceId = boxResponse.getData().getDeviceId();

			ChannelHandlerContext channel = NettyChannelMap.get(deviceId);
			if (channel == null) {
				logger.info(
						LogUtils.build(boxResponse.getMessgeType(), "调用通讯盒", "收到广播调用通讯盒:" + deviceId + " 连接不在本服务，忽略。"));
				return;
			}

			ByteBuf byteBuf = Unpooled.wrappedBuffer(JSON.toJSONString(boxResponse).getBytes(BoxConstants.CHARSET_UTF8));

			channel.writeAndFlush(byteBuf);

			logger.info(LogUtils.build(boxResponse.getMessgeType(), "调用通讯盒",
					"收到广播调用通讯盒成功:" + deviceId + ",流水号:" + boxResponse.getData().getTransacSeq(), JSON.toJSONString(boxResponse)));
		} catch (Exception e) {
			logger.error("收到app广播消息解析失败:" + jsonStr, e);
		}
	}
}
